package com.spring.boot.demo.controller;

import com.spring.boot.demo.utils.RedisLock;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;

/**
 * @author ZhuYouBin
 * @version 1.0.0
 * @Date: 2022/11/9 22:18
 * @Description
 */
@Component
public class TaskDemo01 {

    @Scheduled(cron = "0/10 * * * * ?")
    public void demo01() throws InterruptedException {
        final String key = "distribute_lock_key";
        final String requestId = UUID.randomUUID().toString();
        final long expire = 10000; // 10s过期

        boolean acquireLock = RedisLock.acquireLock(key, requestId, expire);
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String format = sdf.format(new Date());
        if (acquireLock) {
            System.out.println(format + ": [TaskDemo01]模拟操作数据库......");
            // TODO 暂停2秒，释放锁
            Thread.sleep(2000);
            RedisLock.releaseLock(key, requestId);
        } else {
            System.out.println(format + ": [TaskDemo01]获取锁失败,不执行......");
        }
    }

}
